import { defineStore } from 'pinia'
import { v4 as uuidv4 } from 'uuid'
import { db } from '../utils/db'
import { ElMessage } from 'element-plus'

export const useAppStore = defineStore('app', {
  state: () => ({
    applications: [],
    activeAppId: null,
    initialized: false // 新增初始化状态
  }),
  getters: {
    activeApp: (state) => {
      return state.applications.find(app => app.id === state.activeAppId)
    }
  },
  actions: {
    // 新增初始化方法
    async init() {
      try {
        this.initialized = false;
        console.log('开始初始化应用数据...');
        
        console.log('正在打开数据库...');
        let data;
        try {
          data = await db.loadAll();
          console.log('数据库加载成功:', data);
        } catch (dbError) {
          console.error('数据库操作失败:', dbError);
          // 如果数据库操作失败，使用空数组作为默认值
          data = [];
        }
        
        console.log('正在更新应用状态...');
        this.applications = data;
        
        console.log('初始化完成');
        this.initialized = true;
      } catch (error) {
        console.error('初始化失败:', error);
        ElMessage.error('初始化失败，请刷新页面重试');
        this.initialized = true;
      }
    },
    // 新增自动保存方法
    async saveToDB() {
      if (!this.initialized) return
      try {
        await db.saveAll(this.applications)
      } catch (error) {
        console.error('保存数据失败:', error)
      }
    },
    async addApplication(name) {
      const newApp = {
        id: uuidv4(),
        name: name || `新应用${this.applications.length + 1}`,
        workflows: []
      }
      this.applications.push(newApp)
      this.activeAppId = newApp.id
      await this.saveToDB()
    },
    async addWorkflow(workflowData) {
      const app = this.activeApp
      if (app) {
        // 如果传入了工作流数据就使用传入的数据，否则创建新的空工作流
        const newWorkflow = workflowData || {
          id: uuidv4(),
          name: `工作流${app.workflows.length + 1}`,
          nodes: []
        }
        app.workflows.push(newWorkflow)
      }
      await this.saveToDB()
    },
    setActiveApp(appId) {
      this.activeAppId = appId
    },

    async addNode(workflow, nodeData) {
      workflow.nodes.push({
        id: nodeData.id || uuidv4(),
        name: nodeData.name || '新节点',
        description: nodeData.description || '',
        type: nodeData.type || 'static',
        content: nodeData.content || { text: '' },
        input: nodeData.input || '',
        output: nodeData.output || '',
        status: '未执行',
        x: nodeData.x || 0,
        y: nodeData.y || 0
      });
      await this.saveToDB();
    },

    async updateNode(workflowId, nodeId, newData) {
      const workflow = this.getWorkflowById(workflowId)
      const node = workflow?.nodes.find(n => n.id === nodeId)
      if (node) Object.assign(node, newData)
      await this.saveToDB()
    },

    getWorkflowById(workflowId) {
      return this.applications
        .flatMap(app => app.workflows)
        .find(w => w.id === workflowId)
    },

    async deleteNode(workflowId, nodeId) {
      const workflow = this.getWorkflowById(workflowId)
      if (workflow) {
        const nodeIndex = workflow.nodes.findIndex(n => n.id === nodeId)
        if (nodeIndex !== -1) {
          workflow.nodes.splice(nodeIndex, 1)
          await this.saveToDB()
        }
      }
    },

    // 在指定位置插入节点
    async insertNodeAfter(workflowId, targetNodeId, newNode) {
      const workflow = this.getWorkflowById(workflowId)
      if (!workflow) return

      const targetIndex = workflow.nodes.findIndex(n => n.id === targetNodeId)
      if (targetIndex === -1) return

      newNode.status = '未执行'
      workflow.nodes.splice(targetIndex + 1, 0, newNode)
      await this.saveToDB()
    },

    // 在 actions 中添加执行节点的方法
    async executeNode(workflowId, nodeId) {
      let node
      try {
        const workflow = this.getWorkflowById(workflowId)
        if (!workflow) throw new Error('找不到工作流')

        const currentIndex = workflow.nodes.findIndex(n => n.id === nodeId)
        if (currentIndex === -1) throw new Error('找不到当前节点')

        node = workflow.nodes[currentIndex]
        node.status = '执行中'

        // 获取上一个节点的输出（如果存在）
        let inputData = null
        if (currentIndex > 0) {
          const prevNode = workflow.nodes[currentIndex - 1]
          if (prevNode.output) {
            try {
              inputData = JSON.parse(prevNode.output)
            } catch (e) {
              inputData = prevNode.output
            }
            // 将上一个节点的输出设置为当前节点的输入
            node.input = prevNode.output
          }
        }

        // 根据节点类型执行不同的逻辑
        let result = null
        switch (node.type) {
          case 'js':
            try {
              result = await executeInWorker(node.content.code, inputData);
            } catch (error) {
              console.error('Worker execution failed:', error);
              throw new Error('JavaScript执行失败: ' + error.message);
            }
            break

          case 'http':
            const { method, url, headers, body } = node.content
            const headerObj = headers ? JSON.parse(headers) : {}
            const bodyData = body ? JSON.parse(body) : null

            const response = await fetch(url, {
              method,
              headers: headerObj,
              body: bodyData ? JSON.stringify(bodyData) : null
            })
            result = await response.json()
            break

          case 'static':
            // 将固定内容设置为结果
            result = node.content.text
            break
            
          case 'append':
            // 追加文本逻辑
            const inputText = inputData || '';
            const separator = node.content.separator || '————————————';
            const appendText = node.content.text || '';
            
            result = `${inputText}\n${separator}\n${appendText}\n${separator}`;
            break

          case 'ai':
            const aiConfig = node.content
            // 如果提示词为空，使用上一个节点的输出
            const prompt = aiConfig.prompt || inputData || ''
            
            if (aiConfig.streamResponse) {
              // 构建查询参数
              const params = new URLSearchParams({
                prompt,
                model: aiConfig.model,
                temperature: aiConfig.temperature,
                top_p: aiConfig.top_p,
                baseURL: aiConfig.baseURL,
                apiKey: aiConfig.apiKey
              });

              // 创建 EventSource 连接
              const eventSource = new EventSource(`/xz_server/main/getAiModelAnswerStream?${params}`);
              // const eventSource = new EventSource(`http://localhost:7001/main/getAiModelAnswerStream?prompt=hello`);
              let streamContent = '';

              try {
                await new Promise((resolve, reject) => {
                  eventSource.onmessage = (event) => {
                    try {
                      console.log('event.data ==> ', event.data)
                      console.log('event.data === [DONE] ==> ', event.data === '"[DONE]"')
                      console.log('event.data.includes("[DONE]") ==> ', event.data.includes('[DONE]'))
                      // if (event.data.includes('[DONE]')) {
                      if (event.data === '"[DONE]"') {
                        console.log('关闭流式请求')
                        eventSource.close();
                        resolve();
                        return;
                      }

                      const data = JSON.parse(event.data);
                      const content = data.content || '';
                      streamContent += content;
                      
                      // 实时更新节点输出
                      node.output = streamContent;
                      this.saveToDB();
                    } catch (e) {
                      console.error('解析消息失败:', e);
                    }
                  };

                  eventSource.onerror = (error) => {
                    console.error('EventSource error:', error);
                    eventSource.close();
                    reject(new Error('流式请求失败'));
                  };
                });

                result = streamContent;
              } catch (error) {
                console.error('流式请求失败:', error);
                throw error;
              } finally {
                eventSource.close();
              }
            } else {
              // 原有的非流式请求逻辑
              const aiResponse = await fetch('/xz_server/main/getAiModelAnswer', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                  'Authorization': `Bearer ${aiConfig.apiKey}`
                },
                body: JSON.stringify({
                  prompt,
                  model: aiConfig.model,
                  temperature: aiConfig.temperature,
                  top_p: aiConfig.top_p,
                  baseURL: aiConfig.baseURL
                })
              })

              if (!aiResponse.ok) {
                throw new Error(`API请求失败: ${aiResponse.statusText}`)
              }

              const data = await aiResponse.json()
              if (data.error) {
                throw new Error(`API返回错误: ${data.error}`)
              }

              result = data.data?.choices?.[0]?.message?.content || '';
            }
            break;

          default:
            throw new Error('不支持的节点类型')
        }

        // 更新节点状态和输出
        node.output = typeof result === 'string' ? result : JSON.stringify(result, null, 2)
        node.status = '执行成功'
        await this.saveToDB()

        return result
      } catch (error) {
        if (node) {
          node.status = '执行失败'
          node.output = error.message
          await this.saveToDB()
        }
        throw error
      }
    },
    // 在 actions 中添加执行工作流的方法
    async executeWorkflow(workflowId) {
      try {
        const workflow = this.getWorkflowById(workflowId)
        if (!workflow) throw new Error('找不到工作流')

        // 依次执行工作流中的每个节点
        for (const node of workflow.nodes) {
          if (node.type === 'nodata') {
            // 跳过空节点
            continue
          }
          await this.executeNode(workflowId, node.id)
        }

        return true
      } catch (error) {
        throw error
      }
    },
    // 清空单个节点的方法
    async clearNode(workflowId, nodeId) {
      const workflow = this.getWorkflowById(workflowId)
      if (!workflow) return

      const node = workflow.nodes.find(n => n.id === nodeId)
      if (!node) return

      await this.updateNode(workflowId, nodeId, {
        ...node,
        input: '',
        output: '',
        status: '未执行'
      })
    },
    // 清空工作流中所有节点的方法
    async clearWorkflowNodes(workflowId) {
      const workflow = this.getWorkflowById(workflowId)
      if (!workflow) return

      for (const node of workflow.nodes) {
        await this.clearNode(workflowId, node.id)
      }
    },
    // 清空所有工作流中所有节点的方法
    async clearAllNodes() {
      if (!this.activeApp) return

      for (const workflow of this.activeApp.workflows) {
        await this.clearWorkflowNodes(workflow.id)
      }
    },
    async updateWorkflowName(workflowId, newName) {
      const workflow = this.getWorkflowById(workflowId)
      if (workflow) {
        workflow.name = newName
        await this.saveToDB() // 确保保存到数据库
      }
    },
    async deleteWorkflow(workflowId) {
      const app = this.activeApp
      if (!app) return

      const index = app.workflows.findIndex(w => w.id === workflowId)
      if (index !== -1) {
        app.workflows.splice(index, 1)
        await this.saveToDB()
      }
    },
    async deleteApplication(appId) {
      const index = this.applications.findIndex(app => app.id === appId)
      if (index !== -1) {
        this.applications.splice(index, 1)
        await this.saveToDB()
      }
    },
    async updateApplicationName(appId, newName) {
      const app = this.applications.find(a => a.id === appId)
      if (app) {
        app.name = newName
        await this.saveToDB()  // 确保保存到数据库
      }
    },
    // 在 actions 对象中添加新方法
    async executeFromNode(workflowId, nodeId) {
      try {
        const workflow = this.getWorkflowById(workflowId)
        if (!workflow) throw new Error('找不到工作流')

        const startIndex = workflow.nodes.findIndex(n => n.id === nodeId)
        if (startIndex === -1) throw new Error('找不到起始节点')

        // 从指定节点开始执行到最后
        for (let i = startIndex; i < workflow.nodes.length; i++) {
          const node = workflow.nodes[i]
          if (node.type === 'nodata') {
            continue
          }
          await this.executeNode(workflowId, node.id)
        }

        return true
      } catch (error) {
        throw error
      }
    }
  }
})

const executeInWorker = (code, input) => {
  const blob = new Blob([`
    self.onmessage = async function(e) {
      try {
        const input = e.data.input;
        const baseUrl = e.data.baseUrl;
        let output = null;
        
        // 添加辅助函数处理URL
        const resolveUrl = (url) => {
          try {
            return new URL(url).href;
          } catch {
            return new URL(url, baseUrl).href;
          }
        };

        // 重写 fetch 以支持相对路径
        const originalFetch = self.fetch;
        self.fetch = async (url, options) => {
          const resolvedUrl = resolveUrl(url);
          return originalFetch(resolvedUrl, options);
        };

        ${code}
        self.postMessage({ success: true, data: output });
      } catch (error) {
        self.postMessage({ success: false, error: error.message });
      }
    }
  `], { type: 'text/javascript' });

  const worker = new Worker(URL.createObjectURL(blob));
  
  return new Promise((resolve, reject) => {
    worker.onmessage = (e) => {
      if (e.data.success) {
        resolve(e.data.data);
      } else {
        reject(new Error(e.data.error));
      }
      worker.terminate();
    };
    worker.onerror = (error) => {
      reject(new Error(error.message));
      worker.terminate();
    };
    worker.postMessage({
      input: input,
      baseUrl: window.location.origin
    });
  });
}
